from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10,0.2)
driver.get("http://baidu.com")
main_window_handle = driver.current_window_handle
print(main_window_handle)
search_box = wait.until(EC.presence_of_element_located((By.ID, 'chat-textarea')))
search_box.send_keys("帅到惊动联合国", Keys.ENTER)
to_click = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'tts-b-hl')))
to_click.click()
time.sleep(3)

all_handles = driver.window_handles
new_window_handle = all_handles[-1]
driver.switch_to.window(new_window_handle)
driver.close()
driver.switch_to.window(main_window_handle)

search_box = wait.until(EC.presence_of_element_located((By.ID, 'chat-textarea')))
search_box.clear()
search_box.send_keys("洛神赋", Keys.ENTER)
time.sleep(3)
page_source = driver.page_source[:2000]
print("--------源代码为--------")
print(page_source)
with open("洛神赋.txt","w",encoding="utf-8") as f:
    f.write(page_source)
    print("已保存")

input("按回车退出")
driver.quit()



